package com.example.springbootthreadexamples.controller;

import com.example.springbootthreadexamples.service.TestService;
import com.example.springbootthreadexamples.thread.UserContext;
import com.example.springbootthreadexamples.thread.UserContextInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * @author LanWP
 * @date 2024-08-02
 */
@Controller
public class TestThreadController {

    @Autowired
    private TestService testService;
    @Autowired
    private Executor taskExecutor;


    @GetMapping(value="/test")
    public String test() {
        UserContext.setUserContext(new UserContextInfo("123456", "张三", new Date(), LocalDateTime.now()));
        UserContextInfo userContext = UserContext.getUserContext();
        System.out.println(userContext);
        testService.asyncMethod();

        // 异步,默认线程池 ForkJoinPool.commonPool-worker-1
        CompletableFuture.supplyAsync(() -> {
            System.out.println("supplyAsync 异步方法执行中 默认线程池..." + Thread.currentThread().getName() + UserContext.getUserContext());
            System.out.println(UserContext.getUserContext());
            return "ok";
        });

        // 异步
        CompletableFuture.supplyAsync(() -> {
            System.out.println("supplyAsync 异步方法执行中..." + Thread.currentThread().getName() + UserContext.getUserContext());
            System.out.println(UserContext.getUserContext());
            return "ok";
        }, taskExecutor); // 不使用参数 taskExecutor，则使用默认线程池,默认线程池不会复制上下文

        CompletableFuture.runAsync(() -> {
            System.out.println("runAsync 异步方法执行中..." + Thread.currentThread().getName() + UserContext.getUserContext());
            System.out.println(UserContext.getUserContext());
        }, taskExecutor); // 不使用参数 taskExecutor，则使用默认线程池,默认线程池不会复制上下文
        return "ok";
    }
}
